/*
 * iTunes Movie Trailer Import
 * Copyright (c) 2005 Jonathan Bradshaw
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 * documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, 
 * and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 * of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 * TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 * DEALINGS IN THE SOFTWARE. 
 */
using System;
using System.Collections;
using System.Text.RegularExpressions;
using System.Net;
using System.Diagnostics;
using MediaPortal.GUI.Library;
using MediaPortal.Configuration;

namespace ITMSClient
{
	/// <summary>
	/// Summary description for TrailerPage.
	/// </summary>
	public class TrailerIndex
	{
		protected ITMSContent _content			    = null;
		protected TrailerInfoCollection _trailers   = null;
		protected Uri _nextPageUri	                = null;
        protected Uri _backPageUri                  = null;
		protected string _sectionName;

		#region Constructor
		/// <summary>
		/// Creates a new <see cref="TrailerPage"/> instance.
		/// </summary>
		public TrailerIndex(string sectionName, ITMSContent content) 
		{
			this._sectionName = sectionName;
			this._content = content;
		}
		#endregion

		#region Public Properties
		/// <summary>
		/// Returns a read only collection of the trailers.
		/// </summary>
		/// <value></value>
		public TrailerInfoCollection TrailerInfoCollection
		{
			get 
			{ 
				if (_trailers == null)
					ParseIndexPage();
				return TrailerInfoCollection.ReadOnly(_trailers);
			}
		}

		/// <summary>
		/// Gets the content.
		/// </summary>
		/// <value></value>
		public ITMSContent Content
		{
			get { return _content; }
		}

		/// <summary>
		/// Gets the next page URI.
		/// </summary>
		/// <value></value>
		public Uri NextPageUri
		{
			get 
			{ 
                
				if (_nextPageUri == null)
				{
                    
					Match nextPage = RegexParsers.indexNextPageRegex.Match(Content.Xml);
                    
                    if (nextPage.Success)
                    {                        
                        this._nextPageUri = new Uri(Content.WebResponse.ResponseUri, nextPage.Groups["url"].Value);
                        Log.Info("Found next page");
                    }
                    else
                        this._nextPageUri = null;
				}
				return _nextPageUri; 
			}
		}
        public Uri BackPageUri
        {
            get
            {
                Log.Info("backPage uri requested");
                if (_backPageUri == null)
                {
                    Log.Info("backPage currently null");
                    Match backPage = RegexParsers.indexBackPageRegex.Match(Content.Xml);
                    Log.Info("backPage regex performed");
                    if (backPage.Success)
                    {
                        Log.Info("backPage regex successful");
                        this._backPageUri = new Uri(Content.WebResponse.ResponseUri, backPage.Groups["url"].Value);
                        Log.Info("TrailerIndex.BackPageUri - Found previous page");
                    }
                    else
                        this._backPageUri = null;
                }
                return _backPageUri;
            }
        }

		/// <summary>
		/// Gets the count of trailers on the page
		/// </summary>
		/// <value></value>
		public int Count
		{
			get 
			{
				if (_trailers == null)
					ParseIndexPage();
				return _trailers.Count;
			}
		}
		#endregion

		#region Protected Methods
		/// <summary>
		/// Parses the trailers and populates the hashtable
		/// </summary>
		protected void ParseIndexPage()
		{
			
			MatchCollection movieItemCollection = RegexParsers.indexDetailsRegex.Matches(Content.Xml);			
            if (movieItemCollection.Count == 0)
            {
                movieItemCollection = RegexParsers.indexDetailsRegex2.Matches(Content.Xml);
                
                if (movieItemCollection.Count  == 0)
                {
                    movieItemCollection = RegexParsers.indexBoxOfficeRegex.Matches(Content.Xml);
                    if (movieItemCollection.Count == 0)
                    {
                        Log.Info("No movies found in index page xml");
                        return;
                    }
                }
                
            }
            _trailers = new TrailerInfoCollection(movieItemCollection.Count);
            Log.Info("ParseIndexPage - Found {0} trailers.", movieItemCollection.Count);
			foreach (Match movieItem in movieItemCollection)
			{
				Debug.Assert(movieItem.Success);
                TrailerInfo trailerInfo = new TrailerInfo();
				trailerInfo.Url			= new Uri(Content.WebResponse.ResponseUri, movieItem.Groups["url"].Value);
				trailerInfo.Title		= movieItem.Groups["title"].Value;
                if (movieItem.Groups["studio"] != null)
                {
                    trailerInfo.Studio = movieItem.Groups["studio"].Value;
                }
                if (movieItem.Groups["poster"] != null && !String.IsNullOrEmpty(movieItem.Groups["poster"].Value))
                {                    
                    try
                    {
                        String posterUrl = movieItem.Groups["poster"].Value;
                        if (!posterUrl.StartsWith("http://"))
                        {
                            posterUrl = "http://www.apple.com" + posterUrl;
                        }
                        trailerInfo.PosterUrl = new Uri(posterUrl);
                    }
                    catch (Exception e)
                    {
                        Log.Error(e);
                    }
                }
				trailerInfo.Section		= this._sectionName;
				_trailers.Add(trailerInfo);
			}
		}
		#endregion

	}
}
